<template>
	<div class="bg">
		<div class="banner">
			<image :src="banner" mode="widthFix"></image>
		</div>
		<div class="user">
			<div class="">
				<div class="personInfo">
					<div class="ava">
						<image v-if="userInfo.avatarUrl" class="avatar" :src="userInfo.avatarUrl" mode="widthFix"></image>
						<image v-else class="avatar" src="https://www.baixuemianshi.com/zhuanti/images/ava.png" mode="widthFix"></image>
					</div>
					<div class="userDetail">
						<div class="nicknameBox">
							{{userInfo.nickname ? userInfo.nickname : "用户昵称"}}
						</div>
					</div>
				</div>
			</div>
			
		</div>
		<div class="formBox">
			<u-sticky>
			<div class="subBox">
				<div class="container">
					<u-subsection :list="subList" :current="currentPage" @change="sectionChange" mode="subsection" activeColor="#d9232f"></u-subsection>
				</div>
			</div>
			</u-sticky>
			<div class="container">
				<div class="formDetail" v-for="(form,index) in formInfo" :key="index">
					<div class="inpBox" v-for="(inp,j) in form.question" :key="j" v-if="index == currentPage">
						<div class="laebl">{{j + 1}}、{{ inp.title }}-{{form.name}}</div>
						<div class="intro">{{ inp.intro }}</div>
						<div class="inp" v-if="inp.status == 'rate'">
							<u-rate count="10" v-model="inp.answer"></u-rate>
						</div>
						<div class="inp" v-if="inp.status == 'options'">
							<u-radio-group v-model="inp.answer" placement="column" >
							    <u-radio :customStyle="{marginBottom: '8px'}" v-for="(item, k) in inp.options" :key="k" :label="item" :name="item"></u-radio>
							</u-radio-group>
						</div>
						<div class="inp" v-if="inp.status == 'input'">
							<u--input placeholder="请输入内容" border="surround" v-model="inp.answer"></u--input>
						</div>
					</div>
				</div>
			</div>
			<div class="fixBottom">
				<div class="container">
					<div class="btn">
						<u-button type="error" color="#d9232f" shape="circle" text="提交" @click="subForm" v-if="!ansStatus"></u-button>
						<u-button type="error" color="#d9232f" shape="circle" text="您已提交" :disabled="true" v-else></u-button>
					</div>
				</div>
			</div>
			<div class="loadBox" v-if="showLoading">
				<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="加载中..." textSize="20"></u-loading-icon>
			</div>
		</div>
		
		<u-popup :show="showpop" @close="showpop= false" mode="center" :safeAreaInsetBottom="false">
			<div class="popcontent">
				<div class="cell">
					<div class="label">请选择头像</div>
					<div class="w70">
						<div class="ava">
							<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"style="padding: 0; margin: 0;">
								<image v-if="userInfo.avatarUrl" class="avatar" :src="userInfo.avatarUrl" mode="widthFix"></image>
								<image v-else class="avatar" src="https://www.baixuemianshi.com/zhuanti/images/ava.png" mode="widthFix"></image>
							</button>
						</div>
					</div>
				</div>
				<div class="cell">
					<div class="label">请输入昵称</div>
					<div class="w70">
						<div class="nicknameBox">
							<input type="nickname" v-model="userInfo.nickname" @blur="blurname" placeholder="请输入昵称" />
						</div>
					</div>
				</div>
				<div class="">
					<u-button type="error" text="更新信息" @click="showpop = false"></u-button>
				</div>
			</div>
		</u-popup>
		
		<div class="popup" v-if="showPrivacy">
			<div class="popcontent">
				<view class="privacyTit">用户隐私保护提示</view>
				<div class="poptext">感谢您的使用，在使用本小程序前，应当阅读并同意<text
						@click="handleOpenPrivacyContract">《用户隐私保护指引》</text>。当您点击同意并开始使用程序服务时，即表示您已理解并同意该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法进入小程序。
				</div>
				<div class="btns">
					<div class="btn"><u-button shape="circle" @tap="showPrivacy = false">不同意并退出</u-button></div>
					<div class="btn"><u-button type="error" shape="circle" id="agree-btn"
							open-type="agreePrivacyAuthorization"
							@click="handleAgreePrivacyAuthorization">同意并继续</u-button></div>
				</div>
			</div>
		</div>
		
		
	</div>
</template>

<script>
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				banner:"https://www.baixuemianshi.com/zhuanti/images/banner_form.jpg?" + new Date(),
				formInfo:[],
				link:"https://www.baixuemianshi.com/zhuanti/xcx_form/form.js",
				subList:[],
				currentPage:0,
				openid:"",
				ansStatus: false,
				showLoading: false,
				userInfo: {
					_id: "",
					phone: "",
					nickname: "",
					avatarUrl: "",
				},
				showpop:false,
				showPrivacy: false,
			}
		},
		onShareAppMessage(res) {},
		onLoad(options) {
			if (wx.getPrivacySetting) {
				wx.getPrivacySetting({
					success: res => {
						if (res.needAuthorization) {
							this.showPrivacy = true
						} else {
						}
					},
					fail: () => {},
					complete: () => {}
				})
			}
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			}
		},
		created() {
			let that = this;
			that.getopenid()
		},
		mounted() {
			let that = this 
			
		},
		watch: {
			userphone(){
				if(this.userphone){
					console.log(this.userphone)
					this.getUserDetail()
				}
			}
		},
		methods: {
			...mapActions(['LogSetPhone']),
			getopenid() {
				let that = this
				that.showLoading = true
				wx.cloud.callFunction({
					name: 'getopenid',
					data: {},
					complete: res => {
						that.openid = res.result.openid
						that.getForm()
						that.getUserDetail()
					}
				})
			},
			getUserDetail(){
				let that = this
				db.collection('all_user').where({
					_openid: that.openid
				}).get({
					success: res => {
						console.log(res)
						if (res.data.length > 0) {
							that.userInfo._id = res.data[0]._id
							that.userInfo.phone = res.data[0].phone
							that.userInfo.nickname = res.data[0].nickname
							that.userInfo.avatarUrl = res.data[0].avatarUrl
							that.LogSetPhone(that.userInfo.phone)
						}
					}
				})
			},
			getForm(){
				let that = this
				uni.request({
					url: that.link,
					method: 'get',
					dataType: 'text',
					data: {
						sstimes: new Date()
					},
					success: function(res) {
						var resjson = JSON.parse(res.data);
						that.formInfo = resjson
						that.subList = resjson.map(item => item.name)
						that.getAnswer()
					}
				});
			},
			sectionChange(index){
				this.currentPage = index
			},
			async getAnswer(){
				let that = this
				let ans = await db.collection("form_szpf").where({_openid:that.openid}).get()
				if(ans.data.length > 0){
					that.formInfo = ans.data[0].formAnswer
					that.ansStatus = true
				}
				that.showLoading = false
			},
			async subForm(){
				let that = this
				let infoUser = await db.collection("all_user").where({_openid:that.openid}).get()
				if(infoUser.data.length > 0){
					that.getUserDetail()
					that.userInfo.phone = infoUser.data[0].phone
				}
				if(!that.userInfo.phone){
					uni.showToast({
						icon:"error",
						title:"请先登录"
					})
					uni.navigateTo({
						url:"../../my/login?navTlt=真假白雪面试"
					})
					return 
				}
				if(!that.userInfo.nickname || !that.userInfo.avatarUrl){
					uni.showToast({
						icon:"error",
						title:"请授权头像&昵称"
					})
					that.showpop = true
					return
				}
				that.showLoading = true
				let status = that.checkForm()
				if(!status.status){
					uni.showToast({
						icon:"error",
						title:status.user[0] + '信息未填全'
					})
					that.showLoading = false
					return
				}
				db.collection("form_szpf").add({
					data:{
						formAnswer: that.formInfo,
						nickname:that.userInfo.nickname,
						avatarUrl:that.userInfo.avatarUrl,
						time:that.getTime()
					},
					success: res =>{
						uni.showToast({
							icon:"success",
							title:"提交成功"
						})
						that.getAnswer()
					},
					fail:req => {
						that.showLoading = false
					}
				})
				
			},
			checkForm(){
				let that = this
				let sObj = {
					status: true,
					user:[]
				}
				that.formInfo.map((form,index) => {
					let answer = form.question.filter(answer => answer.answer == "")
					if(answer.length > 0){
						sObj.status = false
						sObj.user.push(form.name)
					}
				})
				return sObj
			},
			getTime(){
				let that = this
				let day = new Date()
				let y = day.getFullYear()
				let m = (day.getMonth() + 1).toString().padStart(2, '0');
				let d = day.getDate().toString().padStart(2, '0');
				let hour = day.getHours().toString().padStart(2, '0');
				let miu = day.getMinutes().toString().padStart(2, '0');
				let time = y + '-' + m + '-' + d + ' ' + hour + ':' + miu
				return time
			},
			onChooseAvatar(e) {
				let that = this
				const {
					avatarUrl
				} = e.detail
				uni.uploadFile({
					url: "https://www.baixuemianshi.com/zhuanti/upload_img/xcx2.php",
					filePath: e.detail.avatarUrl,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: res => {
						let status = JSON.parse(res.data) 
						if(status.status == 'success'){
							let link = 'https://www.baixuemianshi.com/zhuanti/upload_img/upload/' + status.data
							that.uploadAva(link)
						}else{
							uni.showToast({
								icon:"error",
								title:"上传失败"
							})
						}  
					}
				})
			},
			uploadAva(link) {
				let that = this
				
				db.collection('all_user').doc(that.userInfo._id).update({
					data: {
						avatarUrl: link
					},
					success: res => {
						that.getUserDetail()
					}
				})
			},
			blurname(e) {
				let that = this
				db.collection('all_user').doc(that.userInfo._id).update({
					data: {
						nickname: e.detail.value
					},
					success: res => {
						that.getUserDetail()
					}
				})
			},
			handleAgreePrivacyAuthorization() {
				this.showPrivacy = false
			},
			handleOpenPrivacyContract() {
				// 打开隐私协议页面
				wx.openPrivacyContract({
					success: () => {}, // 打开成功
					fail: () => {}, // 打开失败
					complete: () => {}
				})
			},
			toLogin() {
				let path = './login??navTlt=' + '个人中心'
				this.changePath(path)
			},
		},
		components: {

		}
	};
</script>

<style>
	@import url(./index.css);
</style>